﻿using Grpc.Core;
using Grpc.Net.Client;
using System;
using System.Threading.Tasks;

namespace GrpcGreeterClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            using var chanel = GrpcChannel.ForAddress("https://localhost:5002");
            var client = new Greeter.GreeterClient(chanel);
            //var reply = await client.SayHelloAsync(
            //      new HelloRequest { Name = "GreeterClient" });
            //Console.WriteLine("Greeting: " + reply.Message);
            //Console.WriteLine("Press any key to exit...");
            //Console.ReadKey();


            using var serverCall = client.StreamingFromServer(new HelloRequest { Name = "StreamingFromServer" });
            await foreach (var response in serverCall.ResponseStream.ReadAllAsync())
            {
                Console.WriteLine("Greeting: " + response.Message);
            }

            using var call = client.StreamingBothWays();
            Console.WriteLine("Starting background task to receive messages");
            var readTask = Task.Run(async () =>
            {
                await foreach (var response in call.ResponseStream.ReadAllAsync())
                {
                    Console.WriteLine(response.Message);
                    // Echo messages sent to the service
                }
            });

            Console.WriteLine("Starting to send messages");
            Console.WriteLine("Type a message to echo then press enter.");
            while (true)
            {
                var result = Console.ReadLine();
                if (string.IsNullOrEmpty(result))
                {
                    break;
                }

                await call.RequestStream.WriteAsync(new HelloRequest { Name = result });
            }

            Console.WriteLine("Disconnecting");
            await call.RequestStream.CompleteAsync();
            await readTask;

            Console.ReadKey();
        }
    }
}
